package com.artogrid.app.contact.controller;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.artogrid.bundle.contact.service.IContactService;
import com.artogrid.framework.global.DynamicDataSourceGlobal;
import com.artogrid.framework.holder.DynamicDataSourceHolder;
import com.artogrid.framework.model.Contact;

@Controller
public class ContactController {
	
	
	@Autowired
	private IContactService service;
	
//	@Autowired
//	private IServiceTest  hornetService;
	
	
	
	@RequestMapping(value="saveContact.do")
	@ResponseBody
	public Contact saveContact(){
		DynamicDataSourceHolder.setDataSourceType(DynamicDataSourceGlobal.data1);// 设置为另一个
		Contact contact = new Contact();
		contact.setName("XXXX");
		contact.setAge((short)26);
		contact.setComment("Hello！");
		contact.setTel("010-27364237");
		service.save(contact);
//		hornetService.sendObjectMessage(contact);
		return contact;
	}
	
	
	@RequestMapping(value="saveContact2.do")
	@ResponseBody
	public Contact saveContact2(){
		DynamicDataSourceHolder.setDataSourceType(DynamicDataSourceGlobal.data2);// 设置为另一个
		Contact contact1 = new Contact();
		contact1.setName("2222");
		service.save(contact1);
//		hornetService.sendObjectMessage(contact);
		return contact1;
	}
	
	
	
	
	@RequestMapping(value="getAll.do")
	@ResponseBody
	public List<Contact> getAll(){
		
		for (Contact contact :service.getAll()){
//			hornetService.sendObjectMessage(contact);
		}
		
		return service.getAll();
	}
	
	
	@RequestMapping(value="login.do")
	@ResponseBody
	public String login(){
		Subject subject = SecurityUtils.getSubject();
		Session session = subject.getSession();
		System.out.println(session.getId());
		// 创建用户名和密码的令牌
		UsernamePasswordToken token = new UsernamePasswordToken("nihao","123456");
		// 记录该令牌，如果不记录则类似购物车功能不能使用。
		token.setRememberMe(true);
		try {
			subject.login(token);
		} catch (UnknownAccountException ex) {
			System.out.println("");
		} catch (IncorrectCredentialsException ex) {
			System.out.println("");
		} catch (AuthenticationException e) {
			e.printStackTrace();
		}
		// 验证是否成功登录的方法
		if (subject.isAuthenticated()) {
			System.out.println("susscess！！");
		}
		return "";
	}
	
	
	
}
